package com.aim.Activity;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Date;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.aim.Service.UploadLocalService;
import com.aim.api.AIMCaseConstants;
import com.aim.util.Preferences;
import com.aim.util.WebServiceUtil;

public class Start extends Activity implements OnClickListener{
	Context mC;
	Button buttonLogin, buttonAbout;
	ProgressDialog progressDialog;
	String usnm, pswd, imei;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	Log.e("1","creat");
    		WebServiceUtil.setContext(this);
    		mC = this;        
    		SharedPreferences sp = mC.getSharedPreferences(Preferences.NAME, 0);
         	usnm = sp.getString(AIMCaseConstants.USERNAME, null);
 			pswd = sp.getString(AIMCaseConstants.PASSWORD, null);
 			imei = sp.getString(AIMCaseConstants.IMEI, null);
	        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	        NetworkInfo netInfo = cm.getActiveNetworkInfo();
	        
 		if (usnm!=null&&pswd!=null&&netInfo!=null&&netInfo.isConnected())
 		{

 			loginProgress();
 			
 		} 
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.start);
        
        buttonLogin = (Button) findViewById(R.id.button1);
        buttonLogin.setOnClickListener(this);
        buttonAbout = (Button) findViewById(R.id.button2); 
        buttonAbout.setOnClickListener(this);
         
        Intent i = new Intent(this, UploadLocalService.class);
    	startService(i);
    	
    	File path = Environment.getExternalStoragePublicDirectory("AIMERR");
    	if(!path.exists())
    	{
    		File p = new File(path.getAbsolutePath()+"/");
    		p.mkdirs();
    	}

    	
    	
    	Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(
    	        path.getAbsolutePath()));
       
    }
    
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
//        setContentView(R.layout.myLayout);
        Log.e("Configuration ","Changed");

      } 
    
    
    public void finish(){
    	
    	mC = null;
    	buttonLogin = null;
    	buttonAbout = null;
    	progressDialog = null;usnm = null;
    	pswd = null;
    	imei = null;;
    	super.finish();
    }
    
    public void onClick(View v) {
    	if (v.equals(buttonLogin)) {

    			Intent log = new Intent(
						Start.this,
						Login.class); 
    			
				startActivity(log);
    	}
    	else if (v.equals(buttonAbout)){


    		Intent about = new Intent(
					Start.this,
					About.class);
			
			startActivity(about);
    		
    	}
    }
    private void loginProgress(){
//    	flagAll = true;

        progressDialog = new ProgressDialog(mC);
        progressDialog.setButton("cancel", new DialogInterface.OnClickListener() {
        	 public void onClick(DialogInterface dialog, int i) {
//        		 flagAll = false;
        	  dialog.cancel();
        	 }
        	});
        progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        	 public void onCancel(DialogInterface dialog) {

        	  progressDialog.dismiss();
        	  
        	 }
        	});
    	progressDialog.setCancelable(true);
    	progressDialog.setMessage("Checking login information, please wait!");

    	progressDialog.show();

    	new Thread(){  
  		  
            @Override  
            public void run() {  
            	
            	Boolean b = WebServiceUtil.login("GetUser",usnm,pswd,imei);
        		
        		
        		
        		if(b){
        			
        			handler.sendEmptyMessage(0);
        			
        		}
            	  
                
            }}.start();
    	
    	
    	
    	 
    }
    
    private Handler handler = new Handler(){  
    	  
        @Override  
        public void handleMessage(Message msg) {  
              
            if(msg.what ==0)
            {
            	try {
					progressDialog.dismiss();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}  
            	
    		
    			
    			Intent mainMenu = new Intent(
						Start.this,
						Main.class);
    			
				startActivity(mainMenu);
            	
            }
           
	          
        }
        };
        public class CustomExceptionHandler implements UncaughtExceptionHandler {

            private UncaughtExceptionHandler defaultUEH;

            private String localPath;


            /* 
             * if any of the parameters is null, the respective functionality 
             * will not be used 
             */
            public CustomExceptionHandler(String localPath) {
                this.localPath = localPath;

                this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();


                
            }

            public void uncaughtException(Thread t, Throwable e) {
            	
//            	Time t = new Time();
//            	Timestamp time = new Timestamp();
            	Date d = new Date();
            	String timestamp = "["+(d.getMonth()+1)+"-"+d.getDate()+"]"+"["+d.getHours()+"-"+d.getMinutes()+"-"+d.getSeconds()+"]";
                final Writer result = new StringWriter();
                final PrintWriter printWriter = new PrintWriter(result);
                e.printStackTrace(printWriter);
                String stacktrace = result.toString();
                printWriter.close();
                String filename = timestamp + ".txt";
                if (localPath != null) {
                    writeToFile(stacktrace, filename);
                }


                defaultUEH.uncaughtException(t, e);
            }

            private void writeToFile(String stacktrace, String filename) {

                try {


                    BufferedWriter bos = new BufferedWriter(new FileWriter(
                            localPath + "/"+ filename ));
                    
                    bos.write(stacktrace);
                    bos.flush();
                    bos.close();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

    
}